package com.example.wire;


import com.example.device.DeviceState;
import com.example.utils.Utils;

public class TwistedPair extends Thread {
    private final Wire wire1;
    private final Wire wire2;
    WireState WS = WireState.INTERVAL;

    //不提供无参构造
    public TwistedPair(Wire wire1, Wire wire2) {
        this.wire1 = wire1;
        this.wire2 = wire2;
    }

    public Wire getWire1() {
        return wire1;
    }

    public Wire getWire2() {
        return wire2;
    }

    private void sendToReceive() {
        while (!(wire1.isSendEmpty() && wire2.isSendEmpty())) {
            wire1.addToReceive(wire2.getFromSend());
            wire2.addToReceive(wire1.getFromSend());
            if (WS == WireState.INTERVAL) {
                WS = WireState.WORKING;
            }
        }
    }

    @Override
    public void run() {
        int multipleTimeDelay = 0;//时延倍数
        while (true) {
            WS = WireState.INTERVAL;
            //双绞线信号交换
            sendToReceive();
            Thread.yield();

            if (WS == WireState.WORKING){
                multipleTimeDelay = 0;
            }else {
                multipleTimeDelay+= 1;
                try {
                    Thread.sleep((long) multipleTimeDelay * Utils.TimeDelay);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    //TODO:以下方法仅用于测试
    public void _sendToReceive() {
        while (!(wire1.isSendEmpty() && wire2.isSendEmpty())) {
            wire1.addToReceive(wire2.getFromSend());
            wire2.addToReceive(wire1.getFromSend());
        }
    }

}
